/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.example.gateway.handler;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.common.base.constant.RedisKeyConstant;
import com.example.common.i18n.api.AjaxJson;
import com.example.common.i18n.util.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR;

/**
 * @author lengleng
 * @date 2018/7/5
 * Hystrix 降级处理
 */
@Slf4j
@Component
public class HystrixFallbackHandler implements HandlerFunction<ServerResponse> {
	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public Mono<ServerResponse> handle(ServerRequest serverRequest) {
		log.error("网关执行请求:{}失败,hystrix服务降级处理", serverRequest.uri());

		final Optional<Object> originalUris = serverRequest.attribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);

		originalUris.ifPresent(originalUri -> log.error("网关执行请求:{}失败,hystrix服务降级处理", originalUri));
		String keyCache = (String) redisTemplate.opsForValue().get(RedisKeyConstant.MICROSERVICES_EXCEPTION_KEY);
		new Thread(() -> {
			if (StrUtil.isBlank(keyCache)) {
				originalUris.ifPresent(originalUri ->  System.out.println("发送系统异常短信"+originalUri));
				redisTemplate.opsForValue().set(keyCache,"MICROSERVICES_EXCEPTION",5, TimeUnit.MINUTES);
				//调用短信服务，发送报警内容
			}else{
				System.out.println("已经发送过短信，5分钟内不重复发送");
			}
		}).start();

		return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
			.contentType(MediaType.APPLICATION_JSON_UTF8).body(BodyInserters.fromObject(JSONObject.toJSONString(MessageUtils.error("当前访问的人数过多，请稍候再试"))));
	}
}
